package com.example.demo.core.controller;

import com.example.demo.core.entity.Menu;
import com.example.demo.core.service.PermissionService;
import com.example.demo.util.PermissionUtil;
import com.example.demo.core.entity.Permission;
import com.example.demo.core.entity.Role;
import com.example.demo.core.service.RoleMenuService;
import com.example.demo.core.service.RolePermissionService;
import com.example.demo.core.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@CrossOrigin
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RolePermissionService rolePermissionService;


    /**
     * 获取所有角色
     */
    @PreAuthorize("hasPermission('roleList', 'users:roles:list')")
    @GetMapping("/roles")
    public List<Role> getRoles(){
        List<Role> roles = roleService.getAllRoles();
        Set<Permission> permissionList;
        for(Role role : roles){
            // 权限表 -> 权限树
            permissionList = new TreeSet<>(PermissionUtil.ListToTree(role.getChildren()));
            role.setChildren(permissionList);
        }
        return roles;
    }

    /**
     * 获取角色
     */
    @GetMapping("/roles/{id}")
    public Role getRole(@PathVariable Integer id) {
//        System.out.println("获取角色对应的数据");
            Role role = roleService.getRoleById(id);
            //System.out.println(role.getChildren());
            // 权限表 -> 权限树
            Set<Permission> permissionList = new TreeSet<>(
                    PermissionUtil.ListToTree(role.getChildren())
            );
            role.setChildren(permissionList);
            // 菜单表 -> 菜单树
            Set<Menu> menusList = new TreeSet<>(
                    PermissionUtil.MenuListToTree(role.getMenus())
            );
            role.setMenus(menusList);
            //System.out.println(role);
            return role;
    }

    /**
    * @Description: 创建角色
    * @Param:  role 角色
    * @return:  保存的角色
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('roleList', 'users:roles:add')")
    @PostMapping("/roles")
    public Role addRole(@RequestBody Role role){
        //System.out.println(role);
        return roleService.addRole(role);
    }

    /**
    * @Description:  删除角色
    * @Param:  id: 角色ID
    * @return:  无
    * @Author: wangze
     */
    @PreAuthorize("hasPermission('roleList', 'users:roles:delete')")
    @DeleteMapping("/roles/{id}")
    public void deleteRole(@PathVariable Integer id){
        roleService.deleteRole(id);
        rolePermissionService.removeByRoleId(id);
        roleMenuService.removeMenuByRoleId(id);
    }

    /**
    * @Description: 删除用户权限
    * @Param:  roleId 角色ID
     * @Param: permissionId 权限ID
    * @return:
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('roleList', 'users:roles:deletepermissions')")
    @DeleteMapping("/roles/{roleId}/permissions/{permissionId}")
    public Set<Permission> removePermissionByRole(@PathVariable("roleId") Integer roleId,
                                                  @PathVariable("permissionId") Integer permissionId){
        rolePermissionService.deleteRolePermission(roleId, permissionId);
        Role role=roleService.getRoleById(roleId);
        Set<Permission> permissionList = new TreeSet<>(
                PermissionUtil.ListToTree(role.getChildren())
        );
        role.setChildren(permissionList);
        return role.getChildren();
    }

    /**
    * @Description: 编辑角色
    * @Param:  id: 角色ID
     * @Param: role: 角色
    * @return:  Role
    * @Author: wangze
    */
    @PreAuthorize("hasPermission('roleList', 'users:roles:update')")
    @PutMapping("/roles/{id}")
    public Role updateRole(@PathVariable("id") Integer id,
                           Role role){
        //System.out.println(role);
        Role roleInDB = roleService.getRoleById(id);
        roleInDB.setName(role.getName());
        roleInDB.setDescription(role.getDescription());
        return roleService.updateRoleById( roleInDB );
    }

    /**
     * 分配权限
     * @param roleId 角色ID
     * @param permissionIdStrings
     */
    @PreAuthorize("hasPermission('roleList', 'users:roles:allotpermissions')")
    @PostMapping("/roles/{id}/permissions")
    public void allotPermissions(@PathVariable("id") Integer roleId,
                                 @RequestParam("idString") String permissionIdStrings){

        // 先清空角色权限和菜单
        rolePermissionService.removeByRoleId(roleId);
        roleMenuService.removeMenuByRoleId(roleId);
        if(permissionIdStrings.equals(""))
            return;
        // 再分配权限
        // "1,22,33" ->["1", "22", "33"]
        String[] permissinIdStrArray = permissionIdStrings.split(",");
        //System.out.println(permissinIdStrArray);
        for(String permissinIdStr : permissinIdStrArray){
            // "22" -> 22
            Integer permissinId = Integer.parseInt(permissinIdStr);
            Permission permission = permissionService.findPermissionById(permissinId);
            if(permission.getOrder()==0||permission.getOrder()==1){
                Integer menuId = permission.getMenuId();
                roleMenuService.addRoleMenu( roleId, menuId);
            }
            rolePermissionService.addRolePermission( roleId, permissinId);
        }
    }
}
